package com.qiguliuxing.dts.admin.web;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.dao.CategorySellVo;
import com.qiguliuxing.dts.admin.dao.OrderAmtsVo;
import com.qiguliuxing.dts.admin.dao.UserOrderCntVo;
import com.qiguliuxing.dts.admin.util.AdminResponseUtil;
import com.qiguliuxing.dts.admin.util.AuthSupport;
import com.qiguliuxing.dts.core.qcode.QCodeService;
import com.qiguliuxing.dts.core.util.RegexUtil;
import com.qiguliuxing.dts.core.util.ResponseUtil;
import com.qiguliuxing.dts.core.util.UUID;
import com.qiguliuxing.dts.core.util.bcrypt.BCryptPasswordEncoder;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.bean.CategorySellAmts;
import com.qiguliuxing.dts.db.bean.DayStatis;
import com.qiguliuxing.dts.db.domain.DtsAdmin;
import com.qiguliuxing.dts.db.domain.DtsUser;
import com.qiguliuxing.dts.db.service.DtsAdminService;
import com.qiguliuxing.dts.db.service.DtsUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.qiguliuxing.dts.admin.util.AdminResponseCode.*;

@RestController
@RequestMapping("/admin/doctor")
@Validated
public class AdminDoctorController {
	private static final Logger logger = LoggerFactory.getLogger(AdminDoctorController.class);

	@Autowired
	private DtsAdminService adminService;
	@Autowired
	private QCodeService qCodeService;
	@Autowired
	private DtsUserService userService;
	private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

	@RequiresPermissions("doctor:doctor:list")
	@RequiresPermissionsDesc(menu = { "系统管理", "A客户管理" }, button = "查询")
	@GetMapping("/list")
	public Object list(String username, String nickName,String belongHospital, String belongDepartment, @RequestParam(defaultValue = "1") Integer page,
					   @RequestParam(defaultValue = "10") Integer limit,
					   @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @Order @RequestParam(defaultValue = "desc") String order) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 系统管理->A客户管理->查询,请求参数:username:{},page:{}", username, page);
		List<DtsAdmin> adminList = adminService.querySelective(username, nickName, belongHospital,belongDepartment,"1", page, limit, sort, order);
		long total = PageInfo.of(adminList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", adminList);

		logger.info("【请求结束】系统管理->A客户管理->查询,响应结果:{}", JSONObject.toJSONString(data));
		return ResponseUtil.ok(data);
	}



	private Object validate(DtsAdmin admin) {
		String name = admin.getUsername();
		if (StringUtils.isEmpty(name)) {
			return ResponseUtil.badArgument();
		}
		if (!RegexUtil.isUsername(name)) {
			logger.error("校验错误：{}", ADMIN_INVALID_NAME.desc());
			return AdminResponseUtil.fail(ADMIN_INVALID_NAME);
		}
		String password = admin.getPassword();
		if (StringUtils.isEmpty(password) || password.length() < 6) {
			logger.error("校验错误：{}", ADMIN_INVALID_PASSWORD.desc());
			return AdminResponseUtil.fail(ADMIN_INVALID_PASSWORD);
		}
		return null;
	}

	@RequiresPermissions("doctor:doctor:create")
	@RequiresPermissionsDesc(menu = { "系统管理", "A客户管理" }, button = "添加")
	@PostMapping("/create")
	public Object create(@RequestBody DtsAdmin admin) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 系统管理->A客户管理->添加,请求参数:{}", JSONObject.toJSONString(admin));

		Object error = validate(admin);
		if (error != null) {
			return error;
		}

		String username = admin.getUsername();
		List<DtsAdmin> adminList = adminService.findAdmin(username);
		if (adminList.size() > 0) {
			logger.error("系统管理->A客户管理->添加 ,错误：{}", ADMIN_NAME_EXIST.desc());
			return AdminResponseUtil.fail(ADMIN_NAME_EXIST);
		}

		String rawPassword = admin.getPassword();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encodedPassword = encoder.encode(rawPassword);
		admin.setPassword(encodedPassword);
		admin.setType("1");



		adminService.add(admin);
		/*
		 * 生成代理用户独有分享的二维码需要小程序已经上线，所以未上线小程序这里调用会异常
		 */
		String shareUrl = qCodeService.createShareUserImage(admin.getId());
		admin.setShareUrl(shareUrl);
		adminService.updateById(admin);
		logger.info("【请求结束】系统管理->A客户管理->添加,响应结果:{}", JSONObject.toJSONString(admin));
		return ResponseUtil.ok(admin);
	}

	@RequiresPermissions("doctor:doctor:read")
	@RequiresPermissionsDesc(menu = { "系统管理", "A客户管理" }, button = "详情")
	@GetMapping("/read")
	public Object read(@NotNull Integer id) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 系统管理->A客户管理->详情,请求参数,id:{}", id);

		DtsAdmin admin = adminService.findById(id);

		logger.info("【请求结束】系统管理->A客户管理->详情,响应结果:{}", JSONObject.toJSONString(admin));
		return ResponseUtil.ok(admin);
	}

	@RequiresPermissions("doctor:doctor:update")
	@RequiresPermissionsDesc(menu = { "系统管理", "A客户管理" }, button = "编辑")
	@PostMapping("/update")
	public Object update(@RequestBody DtsAdmin admin) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 系统管理->A客户管理->编辑,请求参数:{}", JSONObject.toJSONString(admin));

		Object error = validate(admin);
		if (error != null) {
			return error;
		}

		Integer anotherAdminId = admin.getId();
		if (anotherAdminId == null) {
			return ResponseUtil.badArgument();
		}

		String rawPassword = admin.getPassword();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encodedPassword = encoder.encode(rawPassword);
		admin.setPassword(encodedPassword);

		if (adminService.updateById(admin) == 0) {
			logger.error("系统管理->A客户管理-编辑 ,错误：{}", "更新数据失败！");
			return ResponseUtil.updatedDataFailed();
		}

		logger.info("【请求结束】系统管理->A客户管理->编辑,响应结果:{}", JSONObject.toJSONString(admin));
		return ResponseUtil.ok(admin);
	}

	@RequiresPermissions("doctor:doctor:delete")
	@RequiresPermissionsDesc(menu = { "系统管理", "A客户管理" }, button = "删除")
	@PostMapping("/delete")
	public Object delete(@RequestBody DtsAdmin admin) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 系统管理->A客户管理->删除,请求参数:{}", JSONObject.toJSONString(admin));

		Integer anotherAdminId = admin.getId();
		if (anotherAdminId == null) {
			return ResponseUtil.badArgument();
		}

		adminService.deleteById(anotherAdminId);

		logger.info("【请求结束】系统管理->A客户管理->删除 成功！");
		return ResponseUtil.ok();
	}

	@RequiresPermissions("doctor:doctor:create")
	@RequiresPermissionsDesc(menu = { "系统管理", "A客户管理" }, button = "随机获取用户名")
	@PostMapping("/getRandomUserName")
	public Object getRandomUserName(@RequestBody DtsAdmin admin){
		logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 系统管理->A客户管理->随机获取用户名,请求参数:{}", JSONObject.toJSONString(admin));
		Random random = new Random();
		StringBuilder sb = new StringBuilder(5);
		for (int i = 0; i < 5; i++) {
			int index = random.nextInt(ALPHABET.length());
			char randomChar = ALPHABET.charAt(index);
			sb.append(randomChar);
		}
		DtsAdmin lastDtsAdmin = adminService.findLastDtsAdmin();
		if(!ObjectUtils.isEmpty(lastDtsAdmin)){
			sb.append(lastDtsAdmin.getId());
		}
		logger.info("【请求结束】系统管理->A客户管理->随机获取用户名 成功！");
		return ResponseUtil.ok(sb.toString());
	}

	/**
	 * 医生邀请用户
	 * @return
	 */
	@RequiresPermissions("doctor:doctor:invitesMember")
	@RequiresPermissionsDesc(menu = { "基础信息", "邀请用户" }, button = "查询")
	@GetMapping("/invitesMember")
	public Object invitesMember(DtsUser dtsUser,@RequestParam(defaultValue = "1") Integer page,
								@RequestParam(defaultValue = "10") Integer limit,
								@Sort @RequestParam(defaultValue = "add_time") String sort,
								@Order @RequestParam(defaultValue = "desc") String order) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 基础信息->邀请用户, 请求参数:dtsUser:{},page:{}", dtsUser, page);

		dtsUser.setDoctorUserId(AuthSupport.adminId());
		List<DtsUser> dtsUsers = userService.queryByDoctorId(dtsUser,page, limit, sort, order);
		long total = PageInfo.of(dtsUsers).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", dtsUsers);

		logger.info("【请求结束】基础信息->邀请用户:响应结果:{}", JSONObject.toJSONString(data));
		return ResponseUtil.ok(data);
	}

	/**
	 * 会员用户购买记录
	 * @return
	 */
	@RequiresPermissions("doctor:doctor:memberBuyChart")
	@RequiresPermissionsDesc(menu = { "基础信息", "用户购买记录" }, button = "查询")
	@GetMapping("/memberBuyChart")
	public Object memberBuyChart(DtsUser dtsUser,@RequestParam(defaultValue = "1") Integer page,
								 @RequestParam(defaultValue = "10") Integer limit,
								 @Sort @RequestParam(defaultValue = "add_time") String sort,
								 @Order @RequestParam(defaultValue = "desc") String order) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 基础信息->用户购买记录，请求参数:dtsUser:{},page:{}", dtsUser, page);

		dtsUser.setDoctorUserId(AuthSupport.adminId());
		List<Map<String, Object>> list = userService.memberBuyChat(dtsUser,page, limit, sort, order);
		long total = PageInfo.of(list).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", list);

		logger.info("【请求结束】基础信息->用户购买记录:响应结果:{}", JSONObject.toJSONString(data));
		return ResponseUtil.ok(data);
	}

	/**
	 * 用户消费金额
	 * @return
	 */
	@RequiresPermissions("doctor:doctor:memberConsumeAmount")
	@RequiresPermissionsDesc(menu = { "基础信息", "用户消费金额" }, button = "查询")
	@GetMapping("/memberConsumeAmount")
	public Object memberConsumeAmount(DtsUser dtsUser,@RequestParam(defaultValue = "1") Integer page,
									  @RequestParam(defaultValue = "10") Integer limit,
									  @Sort @RequestParam(defaultValue = "add_time") String sort,
									  @Order @RequestParam(defaultValue = "desc") String order) {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 基础信息->用户消费金额，请求参数:dtsUser:{},page:{}", dtsUser, page);

		dtsUser.setDoctorUserId(AuthSupport.adminId());
		List<Map<String, Object>> list = userService.memberConsumeAmount(dtsUser,page, limit, sort, order);
		long total = PageInfo.of(list).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", list);

		logger.info("【请求结束】基础信息->用户消费金额:响应结果:{}", JSONObject.toJSONString(data));
		return ResponseUtil.ok(data);
	}
}
